<template>
  <div class="store-config-container">
    <!-- 商城配置主卡片 -->
    <el-card class="config-card" v-loading="configLoading">
      <template #header>
        <div class="card-header">
          <el-icon><Shop /></el-icon>
          <span>商城配置管理</span>
        </div>
      </template>
      
      <!-- 配置选项卡 -->
      <el-tabs v-model="activeTab" class="config-tabs">
        <!-- 商品管理 -->
        <el-tab-pane label="商品管理" name="products">
          <div class="tab-content">
            <!-- 商品搜索区域 -->
            <div class="search-area">
              <el-form :inline="true" :model="productSearchForm" class="search-form">
                <el-form-item label="商品名称">
                  <el-input 
                    v-model="productSearchForm.productName"
                    placeholder="输入商品名称"
                    clearable
                    @keyup.enter="handleProductSearch"
                  />
                </el-form-item>
                
                <el-form-item label="商品分类">
                  <el-select v-model="productSearchForm.productType" style="width: 100px" placeholder="选择分类" clearable>
                    <el-option label="全部" value="" />
                    <el-option label="精灵" value="SPIRIT" />
                    <el-option label="道具" value="ITEM" />
                    <el-option label="时装" value="COSTUME" />
                    <el-option label="特权" value="PRIVILEGE" />
                    <el-option label="排位" value="PACKAGE" />
                  </el-select>
                </el-form-item>
                
                <el-form-item label="状态">
                  <el-select v-model="productSearchForm.status" style="width: 100px" placeholder="选择状态" clearable>
                    <el-option label="全部" value="" />
                    <el-option label="上架" :value="0" />
                    <el-option label="下架" :value="1" />
                    <el-option label="预售" :value="2" />
                  </el-select>
                </el-form-item>
                
                <el-form-item>
                  <el-button type="primary" @click="handleProductSearch">查询</el-button>
                  <el-button @click="handleProductReset">重置</el-button>
                  <el-button type="success" @click="openAddProductDialog">
                    <el-icon><Plus /></el-icon> 添加商品
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
            
            <!-- 商品列表 -->
            <el-table 
              :data="productList" 
              v-loading="productLoading"
              @selection-change="handleProductSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column label="图片" width="80">
                <template #default="scope">
                  <el-image
                    :src="getFullImageUrl(scope.row.imageUrl)" 
                    class="product-image-thumb"
                  >
                    <template #error>
                      <div class="no-image">无图片</div>
                    </template>
                  </el-image>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="商品名称" min-width="150" />
              <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
              <el-table-column prop="category" label="分类" width="100">
                <template #default="scope">
                  <el-tag :type="getProductTypeTagType(scope.row.category)">{{ getProductTypeName(scope.row.category) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="price" label="价格" width="120">
                <template #default="scope">
                  <span class="price-text">{{ scope.row.price }} {{ scope.row.currencyName }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="stock" label="库存" width="80" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="getProductStatusTagType(scope.row.status)">{{ getProductStatusName(scope.row.status) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="规则" width="120">
                <template #default="scope">
                  <span v-if="scope.row.limitType">
                    {{ scope.row.limitQuantity }}件 / {{ getLimitTypeName(scope.row.limitType) }}
                  </span>
                  <span v-else class="text-muted">无限购</span>
                </template>
              </el-table-column>
              <el-table-column prop="created_at" label="创建时间" width="160">
                <template #default="scope">
                  {{ formatDateFull(scope.row.created_at) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="240" fixed="right">
                <template #default="scope">
                  <div class="operation-buttons">
                    <el-button 
                      type="primary" 
                      text 
                      size="small" 
                      :disabled="scope.row.status === 0"
                      @click="editProduct(scope.row)"
                    >
                      <el-icon><Edit /></el-icon> 编辑
                    </el-button>
                    <el-button 
                      :type="scope.row.status === 0 ? 'warning' : 'success'" 
                      text 
                      size="small"
                      @click="toggleProductStatus(scope.row)"
                    >
                      <el-icon><Switch /></el-icon> 
                      {{ scope.row.status === 0 ? '下架' : '上架' }}
                    </el-button>
                    <el-button type="danger" text size="small" :disabled="scope.row.status === 0" @click="deleteProduct(scope.row)">
                      <el-icon><Delete /></el-icon> 删除
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="productPagination.currentPage"
                v-model:page-size="productPagination.limit"
                :page-sizes="[10, 20, 50, 100]"
                :total="productPagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleProductPageSizeChange"
                @current-change="handleProductPageChange"
              />
            </div>
          </div>
        </el-tab-pane>
        

        
        <!-- 商城设置 -->
        <el-tab-pane label="商城设置" name="settings">
          <div class="tab-content">
            <el-form :model="storeSettings" label-width="160px" class="settings-form">
              <!-- 基础设置 -->
              <div class="section-header">
                <h3 class="settings-section-title">基础设置</h3>
              </div>
              
              <el-form-item label="商城开关">
                <el-switch
                  v-model="storeSettings.store_enabled"
                  active-text="开启"
                  inactive-text="关闭"
                  @change="handleStoreSwitch"
                />
              </el-form-item>
              
              <el-form-item label="商城公告">
                <el-input
                  v-model="storeSettings.store_notice"
                  type="textarea"
                  :rows="3"
                  placeholder="输入商城公告内容"
                />
              </el-form-item>
              
              <!-- 支付设置 -->
              <div class="section-header">
                <h3 class="settings-section-title">支付设置</h3>
              </div>
              
              <el-form-item label="支付方式">
                <el-checkbox-group v-model="storeSettings.payment_methods">
                  <el-checkbox label="diamond">钻石支付</el-checkbox>
                  <el-checkbox label="coin">金币支付</el-checkbox>
                  <el-checkbox label="point">积分支付</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              
              <el-form-item label="钻石汇率">
                <el-input-number
                  v-model="storeSettings.diamond_rate"
                  :min="0.01"
                  :precision="2"
                  :step="0.01"
                />
                <span class="unit-label">元/钻石</span>
              </el-form-item>
              
              <!-- 限制设置 -->
              <div class="section-header">
                <h3 class="settings-section-title">限制设置</h3>
              </div>
              
              <el-form-item label="单日购买限制">
                <el-input-number
                  v-model="storeSettings.daily_purchase_limit"
                  :min="0"
                />
                <span class="unit-label">次</span>
              </el-form-item>
              
              <el-form-item label="单次购买上限">
                <el-input-number
                  v-model="storeSettings.single_purchase_limit"
                  :min="1"
                />
                <span class="unit-label">件</span>
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="saveStoreSettings">
                  <el-icon><Check /></el-icon> 保存设置
                </el-button>
                <el-button @click="resetStoreSettings">
                  <el-icon><RefreshLeft /></el-icon> 重置
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    
    <!-- 添加/编辑商品对话框 -->
    <el-dialog 
      v-model="productDialogVisible" 
      :title="productDialogTitle" 
      width="700px"
      @close="resetProductForm"
    >
      <el-form :model="productForm" :rules="productRules" ref="productFormRef" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.name" placeholder="输入商品名称" />
        </el-form-item>
        
        <el-form-item label="商品分类" prop="productType">
          <el-select v-model="productForm.productType" placeholder="选择分类">
            <el-option label="精灵" value="SPIRIT" />
            <el-option label="道具" value="ITEM" />
            <el-option label="时装" value="COSTUME" />
            <el-option label="特权" value="PRIVILEGE" />
            <el-option label="排位" value="PACKAGE" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="商品价格" prop="price">
          <el-input-number v-model="productForm.price" :min="1" />
        </el-form-item>
        
        <el-form-item label="库存数量" prop="stockQuantity">
          <el-input-number v-model="productForm.stockQuantity" :min="-1" />
        </el-form-item>
        
        <el-form-item label="道具配置">
          <div class="items-config">
            <div v-for="(item, index) in productForm.items" :key="index" class="item-row">
              <el-select 
                v-model="item.itemId" 
                placeholder="输入物品名称搜索"
                style="width: 200px; margin-right: 10px;"
                filterable
                remote
                :remote-method="searchItems"
                :loading="itemLoading"
                clearable
                @change="(value) => handleItemChange(index, value)"
              >
                <el-option
                  v-for="option in itemOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
              <el-input-number 
                v-model="item.num" 
                :min="1" 
                placeholder="数量"
                style="width: 120px; margin-right: 10px;"
                @change="updateProductDescription"
              />
              <el-select 
                v-model="item.itemType" 
                placeholder="道具类型"
                style="width: 150px; margin-right: 10px;"
                @change="updateProductDescription"
              >
                <el-option label="精灵" :value="1" />
                <el-option label="道具" :value="2" />
                <el-option label="时装" :value="3" />
              </el-select>
              <el-button 
                type="danger" 
                text 
                @click="removeItem(index)"
                :disabled="productForm.items.length === 1"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
            <el-button type="primary" text @click="addItem">
              <el-icon><Plus /></el-icon> 添加道具
            </el-button>
          </div>
        </el-form-item>
        
        <el-form-item label="货币类型">
           <el-select-v2 
             v-model="productForm.currencyType" 
             :options="currencyOptions"
             placeholder="选择货币类型"
             style="width: 100%;"
           >
             <template #footer>
               <div style="padding: 12px;">
                 <!-- 新增按钮 -->
                 <div v-if="!showAddCurrency" style="text-align: center;">
                   <el-button type="primary" size="small" @click="handleAddCurrency">
                     <Plus style="width: 14px; height: 14px; margin-right: 4px;" />
                     新增币种
                   </el-button>
                 </div>
                 
                 <!-- 输入框区域 -->
                 <div v-else>
                   <div style="display: flex; align-items: center; margin-bottom: 12px;">
                     <el-input 
                       v-model="newCurrency.id" 
                       placeholder="输入货币ID" 
                       size="small"
                       style="width: 80px; margin-right: 8px;"
                     />
                     <el-input 
                       v-model="newCurrency.name" 
                       placeholder="输入货币名称" 
                       size="small"
                       style="width: 100px;"
                     />
                   </div>
                   <div style="display: flex; justify-content: center;">
                     <el-button size="small" @click="handleCancelAddCurrency" style="margin-right: 8px;">取消</el-button>
                     <el-button type="primary" size="small" :loading="addCurrencyLoading" @click="handleConfirmAddCurrency">确认</el-button>
                   </div>
                 </div>
               </div>
             </template>
           </el-select-v2>
         </el-form-item>
         
         <el-form-item label="商品状态">
           <el-select v-model="productForm.status" placeholder="选择状态">
             <el-option label="上架" :value="0" />
             <el-option label="下架" :value="1" />
             <el-option label="预售" :value="2" />
           </el-select>
         </el-form-item>
         
         <el-form-item label="限购类型">
           <el-select v-model="productForm.limitType" placeholder="选择限购类型" clearable>
             <el-option label="无限购" value="" />
             <el-option label="每日限购" value="1" />
             <el-option label="每周限购" value="2" />
             <el-option label="每月限购" value="3" />
           </el-select>
         </el-form-item>
         
         <el-form-item label="限购数量" v-show="productForm.limitType">
           <el-input-number v-model="productForm.limitQuantity" :min="1" placeholder="输入限购数量" />
         </el-form-item>
         
         <el-form-item label="商品图片">
          <el-input v-model="productForm.imageUrl" placeholder="输入图片地址">
          </el-input>
         </el-form-item>
         
         <el-form-item label="商品描述">
           <el-input v-model="productForm.description" type="textarea" :rows="3" placeholder="输入商品描述" />
         </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="productDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saveLoading" @click="saveProduct">确定</el-button>
      </template>
    </el-dialog>
    

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Shop, Edit, Delete, Plus, Switch, Check, RefreshLeft
} from '@element-plus/icons-vue'
import { getAllProducts, switchProductStatus, addProduct, updateProduct, deleteProduct as deleteProductAPI, uploadImage } from '@/api/officialStore'
import { getCurrency, addCurrency } from '@/api/system'
import { formatDateFull } from '@/utils/utils'
import { findItemsByKeyword, findItemNameById } from '@/utils/itemFinder'
import { getFullImageUrl } from '@/utils'

// 响应式数据
const configLoading = ref(false)
const activeTab = ref('products')

// 商品管理相关
const productLoading = ref(false)
const productList = ref([])
const selectedProducts = ref([])
const productSearchForm = reactive({
  productName: '',
  productType: '',
  status: ''
})
const productPagination = reactive({
  currentPage: 1,
  limit: 10,
  total: 0
})

// 商品对话框
const productDialogVisible = ref(false)
const productDialogTitle = ref('')
const productForm = reactive({
  id: null,
  name: '',
  productType: '',
  price: 0,
  stockQuantity: 0,
  description: '',
  itemIds: '',
  items: [{ itemId: '', itemName: '', num: 1, itemType: 1 }],
  currencyType: 1,
  status: 0,
  imageUrl: '',
  limitType: null,
  limitQuantity: 0
})
const productFormRef = ref()
const productRules = {
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  productType: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
  price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
  stockQuantity: [{ required: true, message: '请输入库存数量', trigger: 'blur' }]
}

// 道具筛选相关
const itemOptions = ref([])
const itemLoading = ref(false)
const saveLoading = ref(false)

// 图片上传相关
const uploadAction = ref('')
const imageUploading = ref(false)
const uploadProgress = ref(0)

// 币种相关
const currencyOptions = ref([])
const newCurrency = reactive({
  id: '',
  name: ''
})
const showAddCurrency = ref(false)
const addCurrencyLoading = ref(false)



// 商城设置
const storeSettings = reactive({
  store_enabled: true,
  store_notice: '',
  payment_methods: ['diamond'],
  diamond_rate: 1.00,
  daily_purchase_limit: 10,
  single_purchase_limit: 99
})

// 方法定义

// 商品管理方法
const handleProductSearch = () => {
  productPagination.currentPage = 1
  loadProductList()
}

const handleProductReset = () => {
  // 重置搜索表单
  productSearchForm.productName = ''
  productSearchForm.productType = ''
  productSearchForm.status = ''
  // 重置分页到第一页
  productPagination.currentPage = 1
  // 执行查询
  loadProductList()
}

const handleProductSelectionChange = (selection) => {
  selectedProducts.value = selection
}

const handleProductPageChange = (page) => {
  productPagination.currentPage = page
  loadProductList()
}

const handleProductPageSizeChange = (size) => {
  productPagination.limit = size
  productPagination.currentPage = 1
  loadProductList()
}

const loadProductList = async () => {
  productLoading.value = true
  try {
    // 构建请求参数
    const params = {
      currentPage: productPagination.currentPage,
      limit: productPagination.limit
    }
    
    // 添加搜索条件
    if (productSearchForm.productName && productSearchForm.productName.trim()) {
      params.productName = productSearchForm.productName.trim()
    }
    if (productSearchForm.productType) {
      params.productType = productSearchForm.productType
    }
    if (productSearchForm.status !== '' && productSearchForm.status !== null && productSearchForm.status !== undefined) {
      params.status = productSearchForm.status
    }
    
    // 调用API
    const response = await getAllProducts(params)
    
    if (response.code === 200) {
      // 映射API数据到页面数据格式
      productList.value = response.data.list.map(item => ({
        id: item.id,
        name: item.name,
        category: item.productType,
        price: item.price,
        stock: item.stockQuantity,
        status: item.status, // 保持原始数字状态值
        created_at: item.created_at,
        currencyType: item.currencyType,
        currencyName: item.currencyName,
        itemIds: item.itemIds,
        description: item.description,
        version: item.version,
        imageUrl: item.imageUrl || '',
        limitType: item.limitType || '',
        limitQuantity: item.maxQuantity || 0
      }))
      
      // 更新分页信息
      productPagination.total = response.data.totalCount
    } else {
      ElMessage.error(response.msg || '加载商品列表失败')
    }
  } catch (error) {
    console.error('加载商品列表失败:', error)
    ElMessage.error('加载商品列表失败')
  } finally {
    productLoading.value = false
  }
}

const openAddProductDialog = () => {
  productDialogTitle.value = '添加商品'
  resetProductForm()
  productDialogVisible.value = true
}

const editProduct = (product) => {
  productDialogTitle.value = '编辑商品'
  
  // 解析itemIds JSON字符串为items数组
  let items = [{ itemId: '', itemName: '', num: 1, itemType: 1 }]
  const editItemOptions = []
  
  if (product.itemIds) {
    try {
      const parsedItems = JSON.parse(product.itemIds)
      if (Array.isArray(parsedItems) && parsedItems.length > 0) {
        items = parsedItems.map(item => {
          
          const itemId = item.itemId || item.itemid || ''
          let itemName = ''
          
          if (itemId) {
            itemName = findItemNameById(itemId, item.itemType || item.type || 1) || ''
            
            // 无论是否找到道具名称，都添加到选项中
            // 如果找不到名称，使用ID作为显示名称
            editItemOptions.push({
              label: itemName || `${itemId}`,
              value: itemId
            })
          }
          
          return {
            itemId: itemId,
            itemName: itemName,
            num: item.num || 1,
            itemType: item.itemType || item.type || 1
          }
        })
      }
    } catch (error) {
      console.warn('解析itemIds失败:', error)
    }
  }
  
  // 设置编辑时的道具选项
  itemOptions.value = editItemOptions
  
  Object.assign(productForm, {
    id: product.id,
    name: product.name,
    productType: product.category,
    price: product.price,
    stockQuantity: product.stock,
    description: product.description,
    itemIds: product.itemIds || '',
    items: items,
    currencyType: product.currencyType || 1,
    status: product.status,
    imageUrl: product.imageUrl || '',
    limitType: product.limitType ? String(product.limitType) : '',
    limitQuantity: product.limitQuantity || 0
  })
  productDialogVisible.value = true
}

const saveProduct = async () => {
  if (!productFormRef.value) return
  
  saveLoading.value = true
  try {
    await productFormRef.value.validate()
    
    // 将items数组转换为JSON字符串，排除itemName字段
    const validItems = productForm.items
      .filter(item => {
        const itemId = String(item.itemId || '').trim()
        return itemId !== ''
      })
      .map(item => ({
        itemId: item.itemId,
        num: item.num,
        itemType: item.itemType
      }))
    const itemIds = JSON.stringify(validItems)
    
    const isEdit = !!productForm.id
    let response
    
    if (isEdit) {
      // 编辑模式：只传递变更的字段
      const originalProduct = productList.value.find(p => p.id === productForm.id)
      const changes = {}
      
      // 检查各字段是否有变更
      if (productForm.name !== originalProduct.name) {
        changes.name = productForm.name
      }
      if (productForm.description !== originalProduct.description) {
        changes.description = productForm.description
      }
      if (productForm.price !== originalProduct.price) {
        changes.price = productForm.price
      }
      if (productForm.currencyType !== originalProduct.currencyType) {
        changes.currencyType = productForm.currencyType
      }
      if (productForm.stockQuantity !== originalProduct.stock) {
        changes.stockQuantity = productForm.stockQuantity
      }
      if (productForm.productType !== originalProduct.category) {
        changes.productType = productForm.productType
      }
      // 比较道具配置是否有变更（深度比较而非字符串比较）
      let originalItems = []
      if (originalProduct.itemIds) {
        try {
          originalItems = JSON.parse(originalProduct.itemIds)
        } catch (error) {
          console.warn('解析原始itemIds失败:', error)
        }
      }
      
      // 深度比较道具配置
      const isItemsChanged = JSON.stringify(validItems) !== JSON.stringify(originalItems)
      if (isItemsChanged) {
        changes.itemIds = itemIds
      }
      if (productForm.status !== originalProduct.status) {
        changes.status = productForm.status
      }
      if (productForm.imageUrl !== (originalProduct.imageUrl || '')) {
        changes.imageUrl = productForm.imageUrl
      }
      // 检查限购相关字段是否有变更
      const limitTypeChanged = productForm.limitType !== (originalProduct.limitType ? String(originalProduct.limitType) : '')
      const limitQuantityChanged = productForm.limitQuantity !== (originalProduct.limitQuantity || 0)
      
      // 如果限购类型或限购数量任一发生变更，两个字段都需要传到后端
      if (limitTypeChanged || limitQuantityChanged) {
        changes.limitType = productForm.limitType ? parseInt(productForm.limitType) : null
        changes.maxQuantity = productForm.limitQuantity
      }
      
      // 如果没有变更，直接关闭对话框
      if (Object.keys(changes).length === 0) {
        ElMessage.info('没有检测到任何变更')
        productDialogVisible.value = false
        return
      }
      
      // 添加商品ID
      changes.id = productForm.id
      
      // 调用修改商品API
      response = await updateProduct(changes)
      
      if (response.code === 200) {
        ElMessage.success('商品修改成功')
        productDialogVisible.value = false
        loadProductList()
      } else {
        ElMessage.error(response.msg || '修改商品失败')
      }
    } else {
      // 添加模式：传递所有字段
      const params = {
        productName: productForm.name,
        productType: productForm.productType,
        price: productForm.price,
        stockQuantity: productForm.stockQuantity,
        itemIds: itemIds,
        description: productForm.description,
        currencyType: productForm.currencyType,
        status: productForm.status,
        imageUrl: productForm.imageUrl,
        limitType: productForm.limitType ? parseInt(productForm.limitType) : null,
        maxQuantity: productForm.limitQuantity
      }
      
      // 调用添加商品API
      response = await addProduct(params)
      
      if (response.code === 200) {
        ElMessage.success('商品添加成功')
        productDialogVisible.value = false
        loadProductList()
      } else {
        ElMessage.error(response.msg || '添加商品失败')
      }
    }
  } catch (error) {
    console.error('保存商品失败:', error)
    ElMessage.error('保存商品失败，请重试')
  } finally {
    saveLoading.value = false
  }
}

const addItem = () => {
  productForm.items.push({ itemId: '', itemName: '', num: 1, itemType: 1 })
  updateProductDescription()
}

const removeItem = (index) => {
  if (productForm.items.length > 1) {
    productForm.items.splice(index, 1)
    updateProductDescription()
  }
}

// 处理道具选择变化
const handleItemChange = (index, itemId) => {
  const option = itemOptions.value.find(opt => opt.value === itemId)
  productForm.items[index].itemId = itemId
  
  if (option) {
    // 如果选项的label是"道具ID: xxx"格式，说明找不到真实名称，尝试重新查找
    if (option.label.startsWith('道具ID: ')) {
      const realName = findItemNameById(itemId, productForm.items[index].itemType)
      productForm.items[index].itemName = realName || ''
    } else {
      productForm.items[index].itemName = option.label
    }
  } else {
    productForm.items[index].itemName = ''
  }
  
  updateProductDescription()
}

// 道具筛选方法
const searchItems = (query) => {
  if (query) {
    itemLoading.value = true
    try {
      const results = findItemsByKeyword(query)
      itemOptions.value = results.map(item => ({
        label: item.name,
        value: item.id
      }))
    } catch (error) {
      console.error('搜索道具失败:', error)
      itemOptions.value = []
    } finally {
      itemLoading.value = false
    }
  } else {
    itemOptions.value = []
  }
}

const resetProductForm = () => {
  Object.assign(productForm, {
    id: null,
    name: '',
    productType: '',
    price: 0,
    stockQuantity: 0,
    description: '',
    itemIds: '',
    items: [{ itemId: '', itemName: '', num: 1, itemType: 1 }],
    currencyType: 1,
    status: 0,
    imageUrl: '',
    limitType: '',
    limitQuantity: 0
  })
  // 清空道具选项
  itemOptions.value = []
  if (productFormRef.value) {
    productFormRef.value.clearValidate()
  }
}

// 自动更新商品描述
const updateProductDescription = () => {
  const descriptions = []
  
  productForm.items.forEach(item => {
    if (item.itemId && item.num) {
      // 使用保存的道具名称，如果没有则使用ID作为fallback
      const itemName = item.itemName || item.itemId
      descriptions.push(`${itemName}x${item.num}`)
    }
  })
  
  productForm.description = descriptions.join('\n')
}

// 监听道具配置变化
watch(
  () => productForm.items,
  () => {
    updateProductDescription()
  },
  { deep: true }
)

const toggleProductStatus = async (product) => {
  try {
    // 设置全局loading状态
    productLoading.value = true
    
    // 调用真实的上下架API
    const newStatus = product.status === 0 ? 1 : 0
    const response = await switchProductStatus({
      productId: product.id,
      status: newStatus
    })
    
    if (response.code === 200) {
      // 切换状态：0(上架) <-> 1(下架)
      product.status = newStatus
      ElMessage.success('操作成功')
    } else {
      ElMessage.error(response.msg || '操作失败')
    }
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    // 重置全局loading状态
    productLoading.value = false
  }
}

const deleteProduct = async (product) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除商品「${product.name}」吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 设置全局loading状态
    productLoading.value = true
    
    // 调用真实的删除API
    const response = await deleteProductAPI(product.id)
    
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadProductList()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  } finally {
    // 重置全局loading状态
    productLoading.value = false
  }
}



// 商城设置方法
const handleStoreSwitch = (value) => {
  ElMessage.success(`商城已${value ? '开启' : '关闭'}`)
}

const saveStoreSettings = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('设置保存成功')
  } catch (error) {
    ElMessage.error('保存设置失败')
  }
}

const resetStoreSettings = () => {
  Object.assign(storeSettings, {
    store_enabled: true,
    store_notice: '',
    payment_methods: ['diamond'],
    diamond_rate: 1.00,
    daily_purchase_limit: 10,
    single_purchase_limit: 99
  })
}

// 工具方法
const getProductTypeName = (productType) => {
  const typeMap = {
    'SPIRIT': '精灵',
    'ITEM': '道具',
    'COSTUME': '时装',
    'PRIVILEGE': '特权',
    'PACKAGE': '排位'
  }
  return typeMap[productType] || productType
}

const getProductTypeTagType = (productType) => {
  const typeMap = {
    'SPIRIT': 'primary',
    'ITEM': 'success',
    'COSTUME': 'warning',
    'PRIVILEGE': 'danger',
    'PACKAGE': 'info'
  }
  return typeMap[productType] || ''
}

const getProductStatusName = (status) => {
  const statusMap = {
    0: '上架',
    1: '下架',
    2: '预售'
  }
  return statusMap[status] || status
}

const getProductStatusTagType = (status) => {
  const typeMap = {
    0: 'success',
    1: 'info',
    2: 'warning'
  }
  return typeMap[status] || ''
}

const getCurrencyName = (currencyType) => {
  const currencyMap = {
    1: 'XIN',
    5: 'XING',
    400503: '徽章'
  }
  return currencyMap[currencyType] || 'XIN'
}

const getLimitTypeName = (limitType) => {
  const limitTypeMap = {
    1: '日',
    2: '周',
    3: '月'
  }
  return limitTypeMap[limitType] || limitType
}

// 图片上传方法
const customUpload = async (options) => {
  const { file, onSuccess, onError } = options
  
  try {
    imageUploading.value = true
    uploadProgress.value = 0
    
    const onUploadProgress = (progressEvent) => {
      if (progressEvent.lengthComputable) {
        uploadProgress.value = Math.round((progressEvent.loaded * 100) / progressEvent.total)
      }
    }
    
    const response = await uploadImage(file, onUploadProgress)
    
    if (response.code === 200) {
      onSuccess(response)
    } else {
      onError(new Error(response.msg || '上传失败'))
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    onError(error)
  } finally {
    imageUploading.value = false
    uploadProgress.value = 0
  }
}

const handleImageSuccess = (response) => {
  if (response.code === 200) {
    productForm.imageUrl = response.path
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.msg || '图片上传失败')
  }
}

const handleImageError = (error) => {
  console.error('图片上传失败:', error)
  ElMessage.error('图片上传失败，请重试')
}

const beforeImageUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error('只能上传 JPG/PNG 格式的图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 触发文件选择
const triggerFileSelect = (event) => {
  // 阻止事件冒泡，避免重复触发
  event.stopPropagation()
  // 找到el-upload组件内的input元素并触发点击
  const uploadInput = event.target.closest('.image-uploader').querySelector('input[type="file"]')
  if (uploadInput) {
    uploadInput.click()
  }
}

// 获取币种数据
const loadCurrencyOptions = async () => {
  try {
    const response = await getCurrency()
    if (response.code === 200) {
      currencyOptions.value = response.data.map(item => ({
        label: item.itemName,
        value: item.itemId
      }))
    } else {
      ElMessage.error(response.msg || '获取币种列表失败')
    }
  } catch (error) {
    console.error('获取币种列表失败:', error)
    ElMessage.error('获取币种列表失败')
  }
}

// 币种管理方法
const handleAddCurrency = () => {
  showAddCurrency.value = true
}

const handleConfirmAddCurrency = async () => {
  if (!newCurrency.id || !newCurrency.name) {
    ElMessage.warning('请填写完整的币种信息')
    return
  }
  
  addCurrencyLoading.value = true
  
  try {
    // 调用添加币种API
    const response = await addCurrency({
      itemId: parseInt(newCurrency.id),
      itemName: newCurrency.name
    })
    
    if (response.code === 200) {
      ElMessage.success('币种添加成功')
      
      // 重置表单并关闭
      newCurrency.id = ''
      newCurrency.name = ''
      showAddCurrency.value = false
      
      // 重新加载币种列表
      loadCurrencyOptions()
    } else {
      ElMessage.error(response.msg || '添加币种失败')
    }
  } catch (error) {
    console.error('添加币种失败:', error)
    ElMessage.error('添加币种失败，请稍后重试')
  } finally {
    addCurrencyLoading.value = false
  }
}

const handleCancelAddCurrency = () => {
  newCurrency.id = ''
  newCurrency.name = ''
  showAddCurrency.value = false
}

// 生命周期
onMounted(() => {
  loadProductList()
  loadCurrencyOptions()
})
</script>

<style scoped>
.store-config-container {
  padding: 20px;
}

.config-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.config-tabs {
  margin-top: 20px;
}

.tab-content {
  padding: 20px 0;
}

.search-area {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.search-form {
  margin: 0;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.price-text {
  color: #f56c6c;
  font-weight: 600;
}

.settings-form {
  max-width: 600px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 30px 0 20px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.section-header:first-child {
  margin-top: 0;
}

.settings-section-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.unit-label {
  margin-left: 8px;
  color: #909399;
  font-size: 14px;
}

/* 操作按钮样式 */
.operation-buttons {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.operation-buttons .el-button {
  margin: 0;
  padding: 6px 12px;
  min-width: auto;
}

.operation-buttons .el-button .el-icon {
  margin-right: 4px;
}

/* 道具配置样式 */
.items-config {
  width: 100%;
}

.item-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.item-row:last-of-type {
  margin-bottom: 15px;
}

/* 图片上传样式 */
.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  width: 148px;
  height: 148px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-uploader:hover {
  border-color: #409eff;
}

.upload-area {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-area:hover {
  background-color: #f0f9ff;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.uploaded-image {
  width: 148px;
  height: 148px;
  object-fit: cover;
  display: block;
}

.upload-progress {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 148px;
  height: 148px;
  padding: 20px;
  box-sizing: border-box;
}

.upload-progress .el-progress {
  width: 100%;
  margin-bottom: 10px;
}

.progress-text {
  font-size: 12px;
  color: #606266;
  text-align: center;
}

.upload-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

/* 商品列表图片缩略图样式 */
.product-image-thumb {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.no-image {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  font-size: 12px;
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .store-config-container {
    padding: 10px;
  }
  
  .search-area {
    padding: 15px;
  }
  
  .search-form {
    display: block;
  }
  
  .search-form .el-form-item {
    margin-bottom: 15px;
  }
  
  .el-table {
    font-size: 12px;
  }
  
  .operation-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
  }
  
  .operation-buttons .el-button {
    margin: 0;
    padding: 4px 8px;
    font-size: 12px;
  }
}

@media (max-width: 480px) {
  .card-header {
    font-size: 14px;
  }
  
  .settings-section-title {
    font-size: 14px;
  }
  
  .el-dialog {
    width: 95% !important;
    margin: 5vh auto;
  }
}

/* 移除可能冲突的el-select__footer样式 */

/* 确保gap属性兼容性 */
.footer-buttons {
  display: flex;
  gap: 8px;
  /* 为不支持gap的浏览器提供fallback */
}

.footer-buttons > * + * {
  margin-left: 8px;
}

/* 移除货币添加区域样式，改用内联样式 */
</style>